import { _decorator, BoxCollider, Component, macro, Node, randomRange, RigidBody, v3, Vec3 } from 'cc';
import { ActorManager } from './ActorManager';
import { Actor } from '../actor/Actor';
import { EffectManager } from './EffectManager';
import { AudioManager } from './AudioManager';
import { StateDefine } from '../actor/StateDefine';
const { ccclass, property } = _decorator;

@ccclass('Level')
export class Level extends Component {

    private static _instance: Level;
    static get instance() {
        return this._instance;
    }

    @property(BoxCollider)
    spawnCollider: BoxCollider = null;

    spawnPos: Vec3 = v3();

    baseHp: number = 100;

    // 一次刷新怪物数量
    count: number = 10;

    // 最大存货怪物数量
    maxAlive: number = 50;

    start() {
        Level._instance = this;
        // 加载资源
        ActorManager.instance.init(()=>{
            EffectManager.instance.init(()=>{
                AudioManager.instance.init();
                this.startLevelTimer();
            })
        })

    }

    onDestroy(): void {
        this.unscheduleAllCallbacks();

        Level._instance = null;
        ActorManager.instance.destroy();
        EffectManager.instance.destroy();
        AudioManager.instance.destroy()
    }

    startLevelTimer(){
        // 刷怪系统
        this.schedule(() => {

            if(!ActorManager.instance.playActor || ActorManager.instance.playActor.currState == StateDefine.Die){
                return;
            }
            if(ActorManager.instance.enemies.length > this.maxAlive){
                return;
            }

            for(let i=0; i < this.count; i++){
                this.randomSpawn();
            }

        }, 10, macro.REPEAT_FOREVER, 2.0);

        // 根据时间,怪物越来越厉害
        this.schedule( ()=>{
            this.baseHp *= 1.2;
        }, 20, macro.REPEAT_FOREVER, 2.0);
    }

    /**
     * 根据出生点范围，随机获取出生点
     */
    randomSpawn() {
        this.spawnPos.x = randomRange(-this.spawnCollider.size.x / 2, this.spawnCollider.size.x / 2);
        this.spawnPos.z = randomRange(-this.spawnCollider.size.z / 2 , this.spawnCollider.size.z / 2);
        this.doSpawn(this.spawnPos);
    }

    /**
     * 生成怪
     * @param pos 坐标
     */
    doSpawn(pos:Vec3){
        const node = ActorManager.instance.createEnemy();
        node.worldPosition = pos;

        let actor = node.getComponent(Actor);
        actor.actorProperty.maxHp = this.baseHp;
        actor.actorProperty.hp = this.baseHp;

        // 随机大小
        let scale = randomRange(1.0, 2.0);
        node.setWorldScale(scale, scale, scale);

        let rigidBody = node.getComponent(RigidBody);
        rigidBody.mass = scale;
    }


    update(deltaTime: number) {
        
    }
}

